package com.jeeww.web.admin.service.menumanage.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jeeww.core.service.impl.BaseServiceImpl;
import com.jeeww.core.syspojo.AgtbMenuInfo;
import com.jeeww.core.syspojo.AgtbMenuInfoDAO;
import com.jeeww.core.syspojo.AgtbResourceInfo;
import com.jeeww.core.syspojo.AgtbResourceInfoDAO;
import com.jeeww.core.syspojo.AgtbResourceMenuRel;
import com.jeeww.core.syspojo.AgtbResourceMenuRelDAO;
import com.jeeww.core.syspojo.AgtbResourceMenuRelId;
import com.jeeww.core.utils.AgileUtils;
import com.jeeww.core.utils.BeanUtilsEx;
import com.jeeww.core.utils.JsonUtils;
import com.jeeww.core.vo.Pager;
import com.jeeww.core.vo.TreeConfig;
import com.jeeww.web.admin.dto.menumanage.MenuManageDTO;
import com.jeeww.web.admin.searchmodel.menumanage.MenuManageSearchModel;
import com.jeeww.web.admin.service.menumanage.MenuManagerService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 类描述：接口.
 * @author 蒋文武
 */
@Service("MenuManagerServiceImpl")
public class MenuManagerServiceImpl extends BaseServiceImpl implements MenuManagerService {
    /**
     * logger.
     */
    private Logger logger = Logger.getLogger(MenuManagerServiceImpl.class);
    /**
     * agtbMenuInfoDAO.
     */
    @Autowired
    private AgtbMenuInfoDAO agtbMenuInfoDAO;
    /**
     * agtbResourceInfoDAO.
     */
    @Autowired
    private AgtbResourceInfoDAO agtbResourceInfoDAO;
    /**
     * agtbResourceMenuRelDAO.
     */
    @Autowired
    private AgtbResourceMenuRelDAO agtbResourceMenuRelDAO;

    @Override
    public String getMenu() throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("service-----获取菜单信息树");
        }
        MenuManageDTO searchModel = new MenuManageDTO();
        TreeConfig tree = new TreeConfig();
        tree.setTreeNamedQueryIdForTree("menuManageQueryAllMenu");
        tree.setTreeNamedQueryIdForCheck("menuManageCheckIsHaveChildren");
        tree.setTreeIdProperty("menuId");
        tree.setTreeNameProperty("menuName");
        String v = JSON.toJSONString(getTreeBySQLNamedQuery(searchModel, tree));
        return v;
    }

    @Override
    public String getMenuResources(final String menuId) throws Exception {
        MenuManageDTO searchModel = new MenuManageDTO();
        searchModel.setMenuId(menuId);
        return getNormalDataBySQLNamedQuery("getMenuResources", searchModel);
    }

    @Override
    public JSONObject saveMenuResource(final String menuId, final String resourceTreeNodes) throws Exception {
        MenuManageSearchModel parametersModel = new MenuManageSearchModel();
        parametersModel.setMenuId(menuId);
        // 删除本菜单原有的关联关系值
        executeDynamicSql("deleteMenuResourceRel", parametersModel);
        String msgKey = null;
        if (!StringUtils.isEmpty(resourceTreeNodes)) {
            AgtbMenuInfo agtbMenuInfo = agtbMenuInfoDAO.get(menuId);
            JSONArray resourceTreeArr = JSONArray.parseArray(resourceTreeNodes);
            List<AgtbResourceMenuRel> entityList = new ArrayList<AgtbResourceMenuRel>();
            for (Object obj : resourceTreeArr) {
                AgtbResourceMenuRel agtbResourceMenuRel = new AgtbResourceMenuRel();
                agtbResourceMenuRel.setAgtbMenuInfo(agtbMenuInfo);
                AgtbResourceInfo agtbResourceInfo = agtbResourceInfoDAO.get(BeanUtilsEx.getProperty(obj, "resourceId"));
                agtbResourceMenuRel.setAgtbResourceInfo(agtbResourceInfo);
                AgtbResourceMenuRelId agtbResourceMenuRelId = new AgtbResourceMenuRelId();
                agtbResourceMenuRelId.setMenuId(agtbMenuInfo.getMenuId());
                agtbResourceMenuRelId.setResourceId(agtbResourceInfo.getResourceId());
                agtbResourceMenuRel.setId(agtbResourceMenuRelId);
                entityList.add(agtbResourceMenuRel);
                // 删除资源信息跟其他菜单的关联关系
                parametersModel.setMenuId(null);
                parametersModel.setResourceId(agtbResourceInfo.getResourceId());
                executeDynamicSql("deleteMenuResourceRel", parametersModel);
            }
            agtbResourceMenuRelDAO.saveList(entityList);
            msgKey = "menuResourceRelUpdateSuccess";
        } else {
            msgKey = "clearMenuResourceRelSuccess";
        }
        return successMsg(msgKey);
    }

    @Override
    public String getMenuResourceInfo(final Pager<?> pager) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("service-----查询资源信息，显示资源信息及其管理菜单信息.");
        }
        String t = getGridBySQLNamedQuery("getMenuResourceInfo", pager);
        return t;
    }

    @Override
    public String getMenuDetail(final MenuManageSearchModel searchModel) throws Exception {
        AgtbMenuInfo agtbMenuInfo = agtbMenuInfoDAO.get(searchModel.getMenuId());
        return JSON.toJSONString(JsonUtils.entity2SimpleJSONObject(agtbMenuInfo));
    }

    @Override
    public JSONObject saveMenu(final MenuManageDTO menuManageDTO) throws Exception {
        String key = menuManageDTO.getMenuId();
        String msgKey = null;
        if (StringUtils.isEmpty(key)) {
            AgtbMenuInfo agtbMenuInfo = new AgtbMenuInfo();
            BeanUtilsEx.copyProperties(agtbMenuInfo, menuManageDTO);
            key = AgileUtils.getKey();
            agtbMenuInfo.setMenuId(key);
            if (agtbMenuInfo.getMenuParentId() == null) {
                agtbMenuInfo.setRootFlag("1");
            }
            agtbMenuInfoDAO.save(agtbMenuInfo);
            msgKey = "saveSuccess";
        } else {
            AgtbMenuInfo agtbMenuInfo = agtbMenuInfoDAO.get(key);
            BeanUtilsEx.copyProperties(agtbMenuInfo, menuManageDTO, true);
            if (agtbMenuInfo.getMenuParentId() == null) {
                agtbMenuInfo.setRootFlag("1");
            }
            agtbMenuInfoDAO.update(agtbMenuInfo);
            msgKey = "updateSuccess";
        }
        JSONObject returnObj = successMsg(msgKey);
        returnObj.put("data", key);
        return returnObj;
    }

    @Override
    public JSONObject deleteMenu(final MenuManageDTO menuManageDTO) throws Exception {
        String key = menuManageDTO.getMenuId();
        // 校验菜单下是否有资源信息，如果有不能删除，必须先删除关联的资源.
        boolean have = getBaseDAO().checkIsHave("checkMenuResource", menuManageDTO);
        if (have) {
            return errorMsg("menuDeleteExceptionMsg");
        }
        agtbMenuInfoDAO.deleteByKey(key);
        return successMsg("deleteSuccess");
    }
}
